package com.teach.javafxclient.controller.base;

import com.teach.javafxclient.Globalvar;
import com.teach.javafxclient.MainApplication;
import com.teach.javafxclient.util.HttpUtil;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import kong.unirest.HttpResponse;
import kong.unirest.json.JSONArray;
import kong.unirest.json.JSONObject;

import java.io.IOException;


public class AcademicPerformanceController {
    @FXML
    private Label completedCredit;
    @FXML
    private Label gpa;
    @FXML
    private Label coursesNumber;
    @FXML
    private ScrollPane Box;
    @FXML
    private GridPane Grp;


    public void set(String studentId) throws IOException {
        JSONObject res = HttpUtil.get(Globalvar.baseUrl + "/api/students/" + studentId + "/scores")
                .asJson().getBody().getObject();
        System.out.println(res);
        if (res.has("scores")) {
            int avgGpa = 0;//还不知道算法
            double totalCredit = 0;
            int row = 0;
            int col = 0;
            double rowHeight = 100.0;
            double commonRowSpacing = 20.0;


            JSONObject dataObject = res.getJSONObject("data");
            JSONArray scoresArray = res.getJSONArray("scores");
            //设置修读学分，gpa
            completedCredit.setText(String.valueOf(dataObject.getDouble("credit")));
            gpa.setText(String.valueOf(dataObject.getDouble("gpa")));
            //加载课程
            for(int i=0;i<scoresArray.length();i++){

                FXMLLoader fxmlLoader = new FXMLLoader(MainApplication.class.getResource("base/academic-performance-item.fxml"));
                Parent root = fxmlLoader.load();
                AcademicPerformanceItemController APIC = fxmlLoader.getController();

                //获取数据
                String courseName = ((JSONObject)scoresArray.get(i)).getJSONObject("course").getString("name");//课程名字
                String teacherName = ((JSONObject)scoresArray.get(i)).getJSONObject("course").getString("teacherName");//教师名字
                String credit = String.valueOf(((JSONObject)scoresArray.get(i)).getJSONObject("course").getDouble("credit"));//单科学分
                String termName = ((JSONObject)scoresArray.get(i)).getJSONObject("course").getString("termName");//学期
                boolean ended =  ((JSONObject)scoresArray.get(i)).getJSONObject("course").getBoolean("ended");//是否结课
                String score = " ";
                if(ended){
                    Object scoreObject = ((JSONObject)scoresArray.get(i)).get("score");//该课程分数
                    if(scoreObject instanceof NullPointerException){
                        score = ((JSONObject)scoresArray.get(i)).getString("grade");//该课程评级
                    }else {
                        // 安全地将Object转换为String
                         score = (String)scoreObject;
                    }
                }


                //布局
                APIC.setItem(courseName,teacherName,credit,termName,ended,score);
                coursesNumber.setText(String.valueOf(scoresArray.length()));

                Grp.add(root,col,row);
                col++;
                if(col == Grp.getColumnCount()){
                    col = 0;
                    row++;
                    RowConstraints rowConstraints = new RowConstraints();//行约束对象
                    rowConstraints.setMinHeight(rowHeight);
                    rowConstraints.setPrefHeight(rowHeight);
                    rowConstraints.setVgrow(Priority.SOMETIMES);//设置行的垂直增长策略:Priority.SOMETIMES意味着当容器有多余的空间时，这一行有时会获得额外的空间。
                    // 这是JavaFX中用于分配额外空间的一种策略，其他可选值还包括Priority.ALWAYS（总是尝试获取额外空间）和Priority.NEVER（从不尝试获取额外空间）。

                    Grp.getRowConstraints().add(rowConstraints);

                    if (row > 1) {
                        Region spacer = new Region();//这里创建了一个Region对象，它通常用作布局中的空白间隔或占位符。Region是一个不包含任何可视内容的Node，但它可以占据空间。
                        Grp.add(spacer, 0, row);
                        rowConstraints = new RowConstraints();
                        rowConstraints.setPrefHeight(commonRowSpacing);
                        Grp.getRowConstraints().add(rowConstraints);
                        Grp.setColumnSpan(spacer, Grp.getColumnCount());
                    }
                }
                totalCredit += ((JSONObject)scoresArray.get(i)).getJSONObject("course").getDouble("credit");
            }
            double totalHeight = (Grp.getRowConstraints().size() * rowHeight) + ((Grp.getRowConstraints().size() - 1) * commonRowSpacing);
            Grp.setPrefHeight(totalHeight);
            Box.setContent(Grp);
        }
        else {
            // 处理data属性不存在的情况，例如记录日志或显示错误消息
            System.out.println("JSONObject[\"scores\"] not found.");
        }
    }
}

